using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using QiAdmin.Core;
using QiAdmin.Core.Services.Cache;
using QiAdmin.Core.Services.Log;
using QiAdmin.Core.Services.Token;
using QiAdmin.Entity;
using QiAdmin.Model.Dtos;
using QiAdmin.Model.Dtos.Input;
using QiAdmin.Model.Dtos.Output;
using QiAdmin.Repository.Repository;
using QiAdmin.Service.IService;
using ICacheService = QiAdmin.Core.Services.Cache.ICacheService;

namespace QiAdmin.Service.Service
{
    /// <summary>
    /// TSysDicData Services
    /// </summary>
    public class TSysDictDataService : BaseService<TSysDictData, TSysDictData_IN, TSysDictData_OUT>, ITSysDictDataService
    {
        readonly TSysDictDataRepository _tSysDictDataRepository;
        readonly TSysDictTypeRepository _tSysDictTypeRepository;
        public TSysDictDataService(ILogService logService,
            ITokenService tokenService, ICacheService cacheService, IHttpContextAccessor httpContextAccessor, TSysDictDataRepository tSysDictDataRepository, TSysDictTypeRepository tSysDictTypeRepository) : base(logService, tokenService, cacheService, httpContextAccessor.HttpContext)
        {
            _tSysDictDataRepository = tSysDictDataRepository;
            _tSysDictTypeRepository=tSysDictTypeRepository;
        }

        #region 增删改查-自动生成

        /// <summary>
        /// 创建默认条件
        /// </summary>
        /// <returns></returns>
        public Expressionable<TSysDictData> CreateExp()
        {
            var exp = Expressionable.Create<TSysDictData>();

            return exp;
        }

        /// <summary>
        /// 新增单条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult Add(TSysDictData_IN input)
        {
            var model = input.Adapt<TSysDictData>();
            int Id = _tSysDictDataRepository.InsertReturnIdentity(model);
            AddDictCache();
            return CommonResult.Convert(Id > 0);
        }

        /// <summary>
        /// 新增多条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult AddRange(List<TSysDictData_IN> input)
        {
            var list = input.Adapt<List<TSysDictData>>();
            var result = _tSysDictDataRepository.InsertRange(list);
            AddDictCache();
            return CommonResult.Convert(result);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult Edit(TSysDictData_IN input)
        {
            var exp = CreateExp();
            exp.And(t => t.Id == input.Id);
            var model = input.Adapt<TSysDictData>();
            var result = _tSysDictDataRepository.UpdateAndIgnore(model, exp.ToExpression());
            AddDictCache();
            return CommonResult.Convert(result);
        }

        /// <summary>
        /// 获取单条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<TSysDictData_OUT> Get(TSysDictData_IN input)
        {
            var exp = CreateExp();
            exp.And(t => t.Id == input.Id);

            var result = _tSysDictDataRepository.GetFirst(exp.ToExpression()).Adapt<TSysDictData_OUT>();
            return new CommonResult<TSysDictData_OUT>(result);
        }

        /// <summary>
        /// 分页获取
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<PageOutput<TSysDictData_OUT>> GetPageList(TSysDictData_IN input)
        {
            var exp = CreateExp();

            exp.AndIF(input.StartQueryTime != DateTime.MinValue, t => t.SysCreateTime >= input.StartQueryTime.Date);
            exp.AndIF(input.EndQueryTime != DateTime.MinValue, t => t.SysCreateTime < input.EndQueryTime.Date.AddDays(1));
            exp.AndIF(!string.IsNullOrEmpty(input.Name), t => t.Name == input.Name);
            exp.AndIF(input.Status == true, t => t.Status == true);
            exp.AndIF(input.TypeId > 0, t => t.TypeId == input.TypeId);
            if (!string.IsNullOrEmpty(input.TypeName))
            {
                int typeId = _tSysDictTypeRepository.GetFirst(p => p.Name == input.TypeName, "未找到字典类型").Id;
                exp.And(t => t.TypeId == typeId);
            }

            PageOutput<TSysDictData_OUT> pageOutput = new PageOutput<TSysDictData_OUT>();
            PageModel pageModel = new() { PageIndex = input.PageIndex, PageSize = input.PageSize };
            pageOutput.Data = _tSysDictDataRepository.GetPageList(exp.ToExpression(), pageModel, t => t.Sort).Adapt<List<TSysDictData_OUT>>();
            pageOutput.DataCount = pageModel.TotalCount;

            return new CommonResult<PageOutput<TSysDictData_OUT>>(pageOutput);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult Remove(TSysDictData_IN input)
        {
            var exp = CreateExp();
            exp.And(t => t.Id == input.Id);

            var result = _tSysDictDataRepository.Delete(exp.ToExpression());
            AddDictCache();
            return CommonResult.Convert(result);
        }

        /// <summary>
        /// 删除多条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult RemoveRange(List<TSysDictData_IN> input)
        {
            var exp = CreateExp();
            exp.And(t => input.Select(s => s.Id).Contains(t.Id));

            var result = _tSysDictDataRepository.Delete(exp.ToExpression());
            AddDictCache();
            return CommonResult.Convert(result);
        }

        #endregion

        /// <summary>
        /// 联表获取类型名称
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<List<TSysDictData_OUT>> GetDataList(TSysDictData_IN input)
        {
            var result = _tSysDictDataRepository.Context.Queryable<TSysDictType>().LeftJoin<TSysDictData>((t, d) => t.Id == d.TypeId).Where((t, d) => t.Status && d.Status).OrderBy((t, d) => d.Sort).Select((t, d) => new TSysDictData_OUT
            {
                Id = d.Id,
                Sort = d.Sort,
                Status = d.Status,
                Name = d.Name,
                TypeId = d.TypeId,
                Value1 = d.Value1,
                Value2 = d.Value2,
                Value3 = d.Value3,
                TypeName = t.Name
            }).ToList();
            return new CommonResult<List<TSysDictData_OUT>>(result);
        }

        /// <summary>
        /// 获取缓存的部门数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public CommonResult<List<TSysDictData_OUT>> GetDictCache()
        {
            var list = _CacheService.Get<List<TSysDictData_OUT>>(App.StaticData.CacheKey_Dict);
            return new CommonResult<List<TSysDictData_OUT>>(list);
        }

        /// <summary>
        /// 缓存部门数据
        /// </summary>
        /// <returns></returns>
        public CommonResult AddDictCache()
        {
            var dictData = GetDataList(new TSysDictData_IN()).Result;
            _CacheService.Add(App.StaticData.CacheKey_Dict, dictData);
            return CommonResult.Success;
        }

    }
}
